using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class MetaScript : MonoBehaviour 
{
	List<productData> product_Type_List;
	public GameObject prod;

	private float currentDifficulty = 0.5f;
	
	public struct productData
	{
		public string name;
		public float weight;
		public Color materialColor;
		public float price;
		public int life;
	}
	
	float warpingTime = 1f;
	
	bool increasedDifficulty = false;
	float increaseTimeSec = 5f;
	float difficultyChangeAmount = 0.1f;
	
	bool popElement = false;
	
	/*
	 * private float weight;
	 * private Color materialColor;
	 * private float price;
	 * 
	 */
	// Use this for initialization
	void Start () 
	{
		this.product_Type_List = new List<productData>();
		this.InitProducts();
	}
	
	void InitProducts()
	{
		this.CreateProduct("Choc", 5f, Color.red, 10f, 1);
		this.CreateProduct("Choc", 15f, Color.grey, 100f, 2);
		
		this.CreateProduct("Choc", 10f, Color.green, 50f, 3);
		this.CreateProduct("Choc", 15f, Color.blue, 60f, 1);
		
		this.CreateProduct("Choc", 15f, Color.blue, 22f, 5);	
		
		this.CreateProduct("Choc", 15f, Color.blue, 62f, 6);
	}
	
	void CreateProduct(string newName, float newWeight, Color newColor, float newPrice, int newLife)
	{
		productData newProductType = new productData();
		
		newProductType.name = newName;
		newProductType.weight = newWeight;
		newProductType.materialColor = newColor;
		newProductType.price = newPrice;
		newProductType.life = newLife;
		
		this.product_Type_List.Add(newProductType);
	}
	
	// Update is called once per frame
	void Update () 
	{
		int currentElement = Random.Range(0, this.product_Type_List.Count);
		
		StartCoroutine(this.popProduct(currentElement));
		StartCoroutine(this.increaseDifficulty());
	}
	
	IEnumerator popProduct(int element)
	{
		if(!this.popElement)
		{
			this.popElement = true;
			
			this.createElement(element);
			
			yield return new WaitForSeconds(this.warpingTime);
			
			this.popElement = false;
		}
	}
	
	void createElement(int element)
	{
		float xPos = Random.Range(-10f, 10f);
		
		GameObject prod = (GameObject) Instantiate(this.prod, new Vector3(xPos, 10f, 0f),this.prod.transform.localRotation);
		
		prod.transform.GetComponent<Product_Script>().Init(
			this.product_Type_List[element].name, this.product_Type_List[element].weight * this.currentDifficulty, 
			this.product_Type_List[element].materialColor, this.product_Type_List[element].price, this.product_Type_List[element].life); 
	}
	
	IEnumerator increaseDifficulty()
	{
		if(!this.increasedDifficulty)
		{
			this.increasedDifficulty = true;
			
			//this.currentDifficulty += this.difficultyChangeAmount/2;
			this.warpingTime -= this.difficultyChangeAmount;
			
			yield return new WaitForSeconds(this.increaseTimeSec);
			
			this.increasedDifficulty = false;
		}
	}
}
